package com.bawei.day11_contentprovider;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 观察者模式：：：：：*****
 1。观察者：督查   小偷
 2。被观察者：韩重唱 运钞车
 3。连接：监控 时刻盯着
 */
public class SMSActivity extends AppCompatActivity {
    private TextView textView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);
        textView = findViewById(R.id.tv);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    "android.permission.WRITE_EXTERNAL_STORAGE",
                    "android.permission.READ_EXTERNAL_STORAGE",
                    "android.permission.READ_CONTACTS",
                    "android.permission.READ_SMS",
                    "android.permission.CALL_PHONE"

            },101);
        }
        //TODO 2:创建观察者对象
        MyObserver myObserver = new MyObserver(handler);
        //TODO 3:被观察者
        ContentResolver contentResolver = getContentResolver();
        //TODO 4:建立链接
        contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI,true,myObserver);

    }
    //TODO 1：定义观察者类 一来短信作出行动
    class  MyObserver extends ContentObserver{
        public MyObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {//一来短信作出行动 查询手机最近的一条短信
            super.onChange(selfChange);

            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
            if(cursor != null){
                cursor.moveToNext();//只获得第一条
                String string = cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
                //TODO 5:正则表达:5位验证码
                Pattern pattern = Pattern.compile("\\d{5}");
                Matcher matcher = pattern.matcher(string);
                if(matcher.find()){//有5个数字
                    String num = matcher.group();
                    textView.setText(num+"");

                }
            }


        }
    }


}
